package com.wedistudio.slideshare.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simpleframework.xml.Serializer;

import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.pool.PoolFactory;
import com.wedistudio.android.framework.service.Service;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.android.framework.service.ServiceRequestConverter;
import com.wedistudio.android.framework.service.ServiceResponseConverter;
import com.wedistudio.slideshare.SlideshareUtils;
import com.wedistudio.slideshare.xml.Slideshow;
import com.wedistudio.slidesprovider.Slide;
import com.wedistudio.slidesprovider.SlideID;

public class GetSlideFromID extends Service<SlideID, Slide> {

	static public GetSlideFromID create() {
		return new GetSlideFromID();
	}

	private static String GET_SLIDESHOW_INFORMATION = "get_slideshow";

	private GetSlideFromID() {
		setRequestConverter(new ServiceRequestConverter<SlideID>() {

			@Override
			public List<URLParams> convert(SlideID request)
					throws ServiceException {
				List<URLParams> result = new ArrayList<URLParams>();
				URLParams params = SlideshareUtils
						.buildURLParams(GET_SLIDESHOW_INFORMATION);
				if (request.getId() != null)
					params.addParam("slideshow_id", request.getId());
				if (request.getUrl() != null)
					params.addParam("slideshow_url", request.getUrl()
							.toString());
				params.addParam("detailed", "1");
				params.addParam("get_transcript", "1");
				result.add(params);
				return result;
			}
		});

		setResponseConverter(new ServiceResponseConverter<Slide>() {

			@Override
			public Slide convert(Map<URLParams, String> raw)
					throws ServiceException {
				Serializer serializer = null;
				try {
					String xml = null;
					for (Map.Entry<URLParams, String> entry : raw.entrySet()) {
						xml = entry.getValue();
						SlideshareUtils.checkResponse(xml);
					}

					serializer = PoolFactory.get(Serializer.class);

					final Slideshow slideshow = serializer.read(
							Slideshow.class, xml);
					Slide slide = slideshow.getSlide();
					slide.populateSlides();
					return slide;
				} catch (ServiceException e) {
					throw e;
				} catch (Throwable e) {
					throw new ServiceException(e);
				} finally {
					PoolFactory.release(serializer, Serializer.class);
				}

			}
		});
	}
}
